package api;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;

/**
 * 小象代理短效代理IP示例 - JAVA，类库 Hutool
 *
 * @author xxdl
 */
public class HutoolDemo {

    // 应用账号（请替换为真实账号）
    private static String appKey = "appKey";
    // 应用密码（请替换为真实密码）
    private static String appSecret = "appSecret";

    private static String api = "http://api.xiaoxiangdaili.com/ip/get?appKey=%s&appSecret=%s&cnt=1&wt=text";
    private static int timeout = 10000;

    private static Proxy getProxy() {
        HttpResponse response = HttpRequest.get(String.format(api, appKey, appSecret)).execute();
        String content = response.body();
        System.out.println("API response: " + content);
        if (!StringUtils.isEmpty(content)) {
            String[] splits = content.split(":");
            if (splits.length == 2) {
                return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(splits[0], Integer.parseInt(splits[1])));
            }
        }
        return null;
    }

    private static void getUrlContent(String url) {
        // JDK 8u111版本后，目标页面为HTTPS协议，启用proxy用户密码鉴权
        System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");

        Authenticator.setDefault(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(appKey, appSecret.toCharArray());
            }
        });

        //发送请求
        HttpResponse result = HttpRequest.get(url)
                .header("Accept-Encoding", "gzip")
                .setProxy(getProxy())
                .timeout(timeout)
                .execute();
        System.out.println(result.body());
    }

    public static void main(String[] args) throws Exception {
        // 要访问的目标页面
        String targetUrl = "http://httpbin.org/ip";
        for (int i = 0; i < 3; i++) {
            getUrlContent(targetUrl);
            Thread.sleep(10000);
        }
    }
}
